// index.js
import {
  get,
  post
} from '../../utils/request'
import {
  APIS
} from '../../utils/api'
import { timestampToTime } from '../../utils/util'
// 获取应用实例
const app = getApp()

Page({
  data: {
    currentIndex: 0,
    currentShopIndex: 0,
    shopArray: [],
    shopIds: [],
    enumArray: [],
    type: '',
    startDate: '-',
    endDate: '-',
    rangeStart: '1990-01-01',
    rangeEnd: '1990-01-01',
    efficient: ''
  },
  onLoad(options) {
    console.log(options);
    this.getEnumData();
    this.getShopData();
    const temp = new Date().getTime();
    const startDate = timestampToTime(temp);
    const endDate = timestampToTime(temp + 24 * 60 * 60 * 1000);
    const rangeEnd = timestampToTime(temp + 365 * 24 * 60 * 60 * 1000);
    this.setData({
      startDate,
      endDate,
      rangeEnd,
      type: options.type
    })
  },
  getShopData() {
    get(APIS.shop).then(res => {
      const list = res.data;
      if (!list.length) {
        return []
      }
      const shopArray = list.map(x => x.name);
      const shopIds = list.map(x => x.id);
      this.setData({
        shopArray,
        shopIds,
      });
    })
  },
  getEnumData() {
    get(APIS.enum).then(res => {
      const list = res.data;
      if (!list.length) {
        return []
      }
      const enumArray = list.map(x => x.name);
      this.setData({
        enumArray,
      });
    })
  },
  bindChangeEnum(e) {
    const currentIndex = e.detail.value;
    this.setData({
      currentIndex
    });
  },
  handleStart(e) {
    let date = e.detail.value;
    let endDate = new Date(date) < new Date(this.data.endDate)
      ? this.data.endDate
      : date
    this.setData({
      startDate: date,
      endDate,
    }, () => {
      this.calcData();
    });
  },
  handleEnd(e) {
    const endDate = e.detail.value;
    this.setData({
      endDate
    }, () => {
      this.calcData();
    });
  },
  calcData() {
    let {startDate, endDate} = this.data;
    // 将字符串日期转换为Date对象  
    const date1 = new Date(startDate);  
    const date2 = new Date(endDate);  
  
    // 计算两个日期之间的差值（毫秒）  
    const diffTime = Math.abs(date2.getTime() - date1.getTime());  
  
    // 将毫秒转换为天  
    const diffDays = Math.ceil(diffTime / (1000 * 3600 * 24)) + 1;  
    this.setData({
      efficient: diffDays
    })
  },
  handleEfficientBlur() {
    console.log(this.data.efficient)
    if (!this.data.efficient || this.data.efficient < 0) {
      this.calcData();
    }
  },
  handleEfficient(e) {
    let {startDate} = this.data;
    let input = e.detail.value;
    if (input <= 0 || !input) {
      return;
    }
    // 10 不用管，算是误差吧
    let endDate = (+new Date(startDate)) + ((input - 1) * 24 * 3600 * 1000) + 10;
    console.log(endDate, startDate)
    let nEnd = new Date(endDate);
    let year = String(nEnd.getFullYear()).padStart(2, '0');
    let month = String(nEnd.getMonth() + 1).padStart(2, '0');
    let day = String(nEnd.getDate()).padStart(2, '0')
    this.setData({
      efficient: input,
      endDate: `${year}-${month}-${day}`
    })
  },
  bindChangeShop(e) {
    const currentShopIndex = e.detail.value;
    this.setData({
      currentShopIndex
    });
  },
  formSubmit(e) {
    console.log(e.detail.value);
    const params = e.detail.value;
    const { start, end, efficient, amount, presentation, shop, eid, number, remain } = params;
    console.log(this.data.type)
    const type = this.data.type;
    // const remainDay = (new Date(end).getTime() - new Date(start).getTime()) / (24 * 3600 * 1000);
    if (type === 'chongzhi' && (!amount || !presentation || !efficient)) {
      wx.showToast({
        title: '缺少必填项',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    else if (type === 'youhui' && (!eid || !amount || !number || !remain)) {
      wx.showToast({
        title: '缺少必填项',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    // else if (Number(efficient) > parseInt(remainDay)) {
    //   wx.showToast({
    //     title: '有效时间超出起止范围',
    //     icon: 'none',
    //     duration: 2000
    //   });
    //   return;
    // };
    post(`${type === 'chongzhi' ? APIS.recharge : APIS.discount}`, {
      ...params,
      sname: this.data.shopArray[shop],
      shop: this.data.shopIds[shop],
      alias: type === 'youhui' ? this.data.enumArray[eid] : undefined
    }).then(res => {
      wx.redirectTo({
        url: `/pages/marketing/index?type=${type}`
      })
    })
  }
})